package dbmonitor

import (
	"reflect"
	"github.com/astaxie/beego/orm"
	"fmt"
	"cloud_worm/util/umodels/mysqldb"
)

type LogCollector struct {
	Id 			int64
	FileName 	string
	Parser 		string
	Created 	int64
	Updated 	int64
	Status 		int
}

func (w *LogCollector) TableName() string {
	return reflect.TypeOf(*w).Name()
}

func (w *LogCollector) Read(fields ...string) error {
	err := orm.NewOrm().Read(w, fields...)
	if err != nil {
		return fmt.Errorf("%s, %s", w.TableName(), err.Error())
	}
	return nil
}

func (w *LogCollector) Update(fields ...string) error {
	_, err := orm.NewOrm().Update(w, fields...)
	if err != nil {
		return fmt.Errorf("%s, %s", w.TableName(), err.Error())
	}
	return nil
}

func (w *LogCollector) Insert() error {
	_, err := orm.NewOrm().Insert(w)
	if err != nil {
		return fmt.Errorf("%s, %s", w.TableName(), err.Error())
	}
	return nil
}

func init()  {
	orm.RegisterModel(new(LogCollector))
}

func (w *LogCollector) Select(offset int, limit int, status int, fileName string) ([]*LogCollector, error) {
	qs := orm.NewOrm().QueryTable(w).Offset(offset).Limit(limit)
	if status != mysqldb.StatusAll {
		qs = qs.Filter("status", status)
	}
	if fileName != mysqldb.SelectStrAll {
		qs = qs.Filter("file_name__istartswith", fileName)
	}

	var l []*LogCollector
	if _, err := qs.All(&l); err != nil {
		return nil, err
	}

	return l, nil
}

func (w *LogCollector) Count(status int, fileName string) (int64, error) {
	qs := orm.NewOrm().QueryTable(w)
	if status != mysqldb.StatusAll {
		qs = qs.Filter("status", status)
	}
	if fileName != mysqldb.SelectStrAll {
		qs = qs.Filter("file_name__istartswith", fileName)
	}

	count, err := qs.Count()
	if err != nil {
		return 0, err
	}
	return count, nil
}